import cn.hutool.core.util.RuntimeUtil;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.FieldAccessor_Ref;
import org.junit.Test;
import org.junit.rules.RunRules;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Proxy;

/**
 * @author Summerday
 */
public class RuntimeTest {


    @Test
    public void testExec(){
        Process process = null;
        try {
            // 打开记事本
            process = Runtime.getRuntime().exec("notepad");
            Thread.sleep(2000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(process != null){
                process.destroy();
            }
        }
    }

    @Test
    public void testAvailableProcessors(){
        System.out.println(Runtime.getRuntime().availableProcessors());
    }

    @Test
    public void testFreeMemory(){
        Runtime r = Runtime.getRuntime();
        System.out.println("处理器个数: " + r.availableProcessors());
        System.out.println("最大内存 : " + r.maxMemory());
        System.out.println("总内存 : " + r.totalMemory());
        System.out.println("剩余内存: " + r.freeMemory());
        System.out.println("最大可用内存: " + getUsableMemory());

        for(int i = 0; i < 10000; i ++){
            new Object();
        }

        System.out.println("创建10000个实例之后, 剩余内存: " + r.freeMemory());
        r.gc();
        System.out.println("gc之后, 剩余内存: " + r.freeMemory());

    }
    /**
     * 获得JVM最大可用内存 = 最大内存-总内存+剩余内存
     */
    private long getUsableMemory() {
        Runtime r = Runtime.getRuntime();
        return r.maxMemory() - r.totalMemory() + r.freeMemory();
    }


    @Test
    public void testAddShutdownHook() throws InterruptedException {
        Runtime.getRuntime().addShutdownHook(new Thread(()-> System.out.println("programming exit!")));
        System.out.println("sleep 3s");
        Thread.sleep(3000);
        System.out.println("over");
    }


    @Test
    public void testRemoveShutdownHook() throws InterruptedException {
        Thread thread = new Thread(()-> System.out.println("programming exit!"));
        Runtime.getRuntime().addShutdownHook(thread);
        System.out.println("sleep 3s");
        Thread.sleep(3000);
        Runtime.getRuntime().removeShutdownHook(thread);
        System.out.println("over");
    }

    @Test
    public void testExit(){
        Runtime.getRuntime().exit(0);
        //下面这段 无事发生
        System.out.println("Program Running Check");
    }

    @Test
    public void testHalt(){
        Runtime r = Runtime.getRuntime();
        r.halt(0);
        System.out.println("process is still running");
    }


}
